package com.wispx.gateway.core.filter.loadblance.strategy;

import com.wispx.gateway.config.pojo.ServiceInstance;
import com.wispx.gateway.core.context.GatewayContext;
import io.netty.util.internal.ThreadLocalRandom;

import java.util.List;

import static com.wispx.gateway.common.constant.LoadBalanceConstant.WEIGHT_LOAD_BALANCE_STRATEGY;

/**
 * 权重负载均衡
 */
public class WeightLoadBalacneStrategy implements LoadBalanceStrategy {
    @Override
    public ServiceInstance selectInstance(GatewayContext context, List<ServiceInstance> instances) {
        int totalWeight = instances.stream()
                .mapToInt(ServiceInstance::getWeight)
                .sum();
        if (totalWeight <= 0) {
            return null;
        }
        // 根据总权重生成随机权重
        int randomWeight = ThreadLocalRandom.current().nextInt(totalWeight);
        for (ServiceInstance instance : instances) {
            randomWeight -= instance.getWeight();
            if (randomWeight <= 0) {
                return instance;
            }
        }
        return null;
    }

    @Override
    public String mark() {
        return WEIGHT_LOAD_BALANCE_STRATEGY;
    }
}
